package com.oktest.measure.xml

import com.oktest.measure.MyApp
import com.oktest.measure.entity.Device
import com.oktest.measure.entity.Measure
import com.oktest.measure.entity.Type
import com.oktest.measure.entity.Xml
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.InputStream

/**
 * @Author hhh
 * @Date 2020/9/20
 */
object XmlPullHelper {

    private var xml = Xml()
    private var device = Device()
    private var type = Type()
    private var measure = Measure()
    private lateinit var parser:XmlPullParser

    private val measureList = arrayListOf<Measure>()
    private val typeList = arrayListOf<Type>()
    private val deviceList = arrayListOf<Device>()

    fun parseTask(ins: InputStream) {
        val factory = XmlPullParserFactory.newInstance()
        parser = factory.newPullParser()
        parser.setInput(ins, "utf-8")
        var type = parser.eventType
        while (type != XmlPullParser.END_DOCUMENT) {
            when (type) {
                XmlPullParser.START_DOCUMENT -> {

                }
                XmlPullParser.START_TAG -> {
                    setEntity()
                }
                XmlPullParser.END_TAG -> {

                }
            }
            type = parser.next()
        }
        MyApp.roomDatabase.apply {
            xmlDao().insert(xml)
            deviceDao().insert(deviceList)
            typeDao().insert(typeList)
            measureDao().insert(measureList)
        }
    }

    private fun setEntity() {
        "element ".log(parser.name)
        when (parser.name) {
            TASKS -> {
                xml.apply {
                    id = "id".attr().toLong()
                    name = "name".attr()
                }
            }
            TASK -> {
                device = Device().apply {
                    id = "id".attr().toLong()
                    name = "name".attr()
                    rate = "rate".attr()
                    xmlId = xml.id
                }
                deviceList.add(device)
            }
            METERAGE -> {
                type = Type().apply {
                    id = "id".attr().toLong()
                    type = "type".attr()
                    name = "name".attr()
                    deviceId = device.id
                }
                typeList.add(type)
            }
            MEASURE -> {
                measure = Measure().apply {
                    id = "id".attr().toLong()
                    value = "value".attr()
                    angle = "angle".attr()
                    sc = "sc".attr()
                    sv = "sv".attr()
                    typeId = type.id
                    rate = device.rate
                }
                measureList.add(measure)
            }
        }
    }
    private fun String.attr(): String {
        return parser.getAttributeValue(null, this)?:""
    }
}